package com.yu.common.service;

import com.yu.common.constant.Const;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;

@Slf4j
@Service
public class LockService {

    @Resource
    private RedisTemplate redisTemplate;


    // **************** 乐观锁 ***************** //
    public boolean tryLock(String key, String value, long time) {
        try {
            return redisTemplate.opsForValue()
                    .setIfAbsent(Const.CONST_user_take_order_lock_prefix + key, value, Duration.ofSeconds(time));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    public boolean releaseLock(String key) {
        return redisTemplate.delete(Const.CONST_user_take_order_lock_prefix + key);
    }
}
